#include "config.h"

FILE* g_cfgfile = NULL;
char **g_cfgbuf;
static int g_cfgmaxline;

void cfg_open(const char* filepath)
{
    g_cfgbuf = (char**) malloc (1024 * sizeof(char*));
    g_cfgfile = fopen(filepath, "rt");
    if (g_cfgfile == NULL)
    {
        fprintf(stderr,"Cannot open config file");
        return;
    }
    
    char line[MAXLINELENGTH];
    memset(line, 0, MAXLINELENGTH);
    g_cfgmaxline = 0;
    while (fscanf(g_cfgfile, "%s", line) != EOF)
    {
        // skip comments
        if ((line[0]  == '/' && line[1] == '/') || line[0] == ';' || line[0] == '#')
        {
            continue;
        }

        g_cfgbuf[g_cfgmaxline] = (char*) malloc(MAXLINELENGTH * sizeof(char));
        strncpy(g_cfgbuf[g_cfgmaxline], line, MAXLINELENGTH);
        g_cfgmaxline++;
    }

    printf("Config file (%s) loaded. %d lines read\n", filepath, g_cfgmaxline);
}

char* cfg_getstr(const char* key, const char* defaultVal)
{
    for(int i = 0 ; i < g_cfgmaxline; i++)
    {
        if (strstr(g_cfgbuf[i], key) == g_cfgbuf[i])
        {
            char *val = strchr(g_cfgbuf[i], '=');
            if (val != NULL)
            {
                return val+1;
            } else
            {
                return (char*) defaultVal;
            }
        }
    }
    return (char*) defaultVal;
}

// returns a string in an array
char* cfg_getstr(const char* key, int offset, const char* defaultVal){

	char* val = cfg_getstr(key, defaultVal);

	char* str = strtok(val, ",. ;:");
	int off = 0;

	while(str != NULL)
  {
		if (off == offset)
    {
			return str;
		}
		str = strtok(NULL, ",. ;:");
		off++;
	}

	if (str == NULL && off > offset)
  {
		return NULL;
	}

}

int cfg_getint(const char* key, int defaultVal)
{
    char* val = cfg_getstr(key, DUMMYSTR);

    if (strcmp(val, DUMMYSTR) != 0)
    {
        return atoi(val);
    }

    return defaultVal;
}

float cfg_getfloat(const char* key, float defaultVal)
{
    char* val = cfg_getstr(key, DUMMYSTR);

    if (strcmp(val, DUMMYSTR) != 0)
    {
        return (float) atof(val);
    }

    return defaultVal;
}

void cfg_close()
{
    if (g_cfgfile != NULL)
    {
        fclose(g_cfgfile);
    }

    for(int i = 0 ; i < g_cfgmaxline; i++)
    {
        delete[] g_cfgbuf[i];
    }

    delete[] g_cfgbuf;
}

